//
//  RunTimeModel.m
//  RunTime
//
//  Created by 吴志勇 on 2020/3/29.
//  Copyright © 2020 wzy. All rights reserved.
//

#import "RunTimeModel.h"
#import <objc/message.h>

@implementation RunTimeModel

+ (instancetype)modelWithDict:(NSDictionary *)dict{
    id objc = [[self alloc] init];
    //runtime:遍历模型中所有成员属性，去字典中查找
    //遍历模型所有成员属性
    //ivar // 成员属性
//    class_copyIvarList 把成员属性列表复制一份给你
    unsigned int count = 0; // 成员属性总数
    Ivar *ivarList =  class_copyIvarList(self, &count);
    for (int i = 0; i < count; i++) {
        Ivar ivar = ivarList[i];
        //获取成员名，成员属性类型
        NSString *propertyName = [NSString stringWithUTF8String:ivar_getName(ivar)];
        NSString *propertyType = [NSString stringWithUTF8String:ivar_getTypeEncoding(ivar)];
        //获取字典中的key
        NSString *key = [propertyName substringFromIndex:1];
        
        id value =  dict[key];
        
        
        //二级转换
        if ([value isKindOfClass:[NSDictionary class]] && ![propertyType containsString:@"NS"]) {
            //转换成哪个类型
            
            //@"@\"xx\"" //需要字符串截取
            NSRange range = [propertyType rangeOfString:@"\""];
            propertyType = [propertyType substringFromIndex:range.location + range.length];
            
            range = [propertyType rangeOfString:@"\""];
            propertyType = [propertyType substringToIndex:range.location];
            
            
            
            //获取需要转换类的类对象
            Class modelClass = NSClassFromString(propertyType);
            if (modelClass) {
                value = [modelClass modelWithDict:value];
            }
        }
        
        if (value) {
             [objc setValue:value forKey:key];
        }
        
       
    }
    
    return objc;
}

- (void)setValue:(id)value forUndefinedKey:(NSString *)key{
    
}

@end
